//
//  SetWiFiStampVC.m
//  dyseller
//
//  Created by 红喇叭 on 2017/11/7.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "SetWiFiStampVC.h"
#import "RollSelect.h"

@interface SetWiFiStampVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    
    UILabel *_stampClass;
    UITextField *SNtextfield;
    UITextField *Keytextfield;
}

@property(nonatomic,strong)UITableView *stampTableView;

@property(nonatomic,strong)UILabel *stampNum;

@end

@implementation SetWiFiStampVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavTitle:@"设置打印机" titleColor:[UIColor blackColor] font:font17];
    [self.view addSubview:self.stampTableView];
    
    UIButton *rightbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightbtn setTitle:@"删除" forState:0];
    [rightbtn setTitleColor:[UIColor blackColor] forState:0];
    [rightbtn addTarget:self action:@selector(deleteStamp) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightbtn];
    if(_isNewStamp) rightbtn.hidden = YES;
    if(_isNewStamp) _stampInfo = @{@"printer_format":@"1"}.mutableCopy;
    
   
}

- (UITableView *)stampTableView{
    if(_stampTableView == nil){
        _stampTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _stampTableView.delegate = self;
        _stampTableView.dataSource = self;
        _stampTableView.estimatedSectionFooterHeight = 0 ;
        _stampTableView.estimatedSectionHeaderHeight = 0;
        _stampTableView.estimatedRowHeight = 60;
        _stampTableView.backgroundColor = self.view.backgroundColor;
    }
    return  _stampTableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


- (void)updateStampNumber:(UIButton *)btn{
    if(btn.tag == 0){//减 按钮
        if([_stampNum.text integerValue] == 1){
            [AlertUtils showToastWithMessage:@"纸张数量不能少于1" inView:self.view hideAfterDelay:1.0 beIndeter:NO];
            return;
        }
        _stampNum.text = [NSString stringWithFormat:@"%ld",[_stampNum.text integerValue]-1];
    }else{
        _stampNum.text = [NSString stringWithFormat:@"%ld",[_stampNum.text integerValue]+1];
    }
}

#pragma  mark ========商家，后厨选择的页面========
- (void)showRooll{
    
   RollSelect* selectVC = [[RollSelect alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-150-64, SCREEN_W, 150) dataArray:@[@"商家联",@"后厨联"]];
    
    selectVC.blcok = ^(NSString *value) {
        _stampClass.text = value;
        [selectVC removeFromSuperview];
    };
    [self.view addSubview:selectVC];
}

#pragma  mark ========保存打印机信息========
- (void)saveStampInfo{
    if(SNtextfield.text.length<5){
        [AlertUtils showToastWithMessage:@"请填写正确的设备SN" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        return;
    }
    if(Keytextfield.text.length<4){
         [AlertUtils showToastWithMessage:@"请填写正确的设备KEY" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        return;
    }
    NSMutableDictionary *dic = _stampInfo.mutableCopy;
    [dic setObject:SNtextfield.text forKey:@"printer_sn"];
    [dic setObject:Keytextfield.text forKey:@"printer_key"];
    [dic setObject:@"2" forKey:@"printer_type"];
    [dic setObject:[_stampClass.text isEqualToString:@"商家联"]?@"1":@"2" forKey:@"printer_flag"];
    [dic setObject:_stampNum.text forKey:@"printer_times"];
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Print/setPrinter" parameter:dic successBlock:^(PPHttpRequest *request, id responseObj) {
        
        [AlertUtils showToastWithMessage:@"保存成功" inView:self.view hideAfterDelay:1.0 beIndeter:NO];
        [self.navigationController popViewControllerAnimated:YES];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];

}

- (void)deleteStamp{
    
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Print/delPrinter" parameter:@{@"printer_sn":SNtextfield.text,@"printer_key":Keytextfield.text} successBlock:^(PPHttpRequest *request, id responseObj) {
        
            [self.navigationController popViewControllerAnimated:YES];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];
}

#pragma  mark ========测试打印========
- (void)stampTest{
    
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Print/printerTest" parameter:@{@"printer_sn":SNtextfield.text,@"printer_key":Keytextfield.text} successBlock:^(PPHttpRequest *request, id responseObj) {
        
         [AlertUtils showToastWithMessage:@"打印成功" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];
}


#pragma  mark ========UITableViewDelegate UITableViewDataSouce========
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    UILabel *lab = [[UILabel alloc] init];
    [cell.contentView addSubview:lab];
    lab.sd_layout.leftSpaceToView(cell.contentView, 15).centerYEqualToView(cell.contentView).widthIs(100).autoHeightRatio(0);
    if(indexPath.section == 0){
        if(indexPath.row == 0){
            lab.text = @"打印样式";
            UIImageView *leftimg = [[UIImageView alloc] init];
            leftimg.image = [UIImage imageNamed:@"print_button4_default"];
            [cell.contentView addSubview:leftimg];
            leftimg.sd_layout.rightSpaceToView(cell.contentView, 15).centerYEqualToView(cell.contentView).widthIs(100).heightIs(30);
            _stampClass = [[UILabel alloc] init];
            if(_isNewStamp){
               _stampClass.text = @"商家联";
            }else{
                _stampClass.text =[_stampInfo[@"printer_flag"] isEqualToString:@"1"]?@"商家联":@"后厨联";
            }
            
            [leftimg addSubview:_stampClass];
            _stampClass.sd_layout.leftSpaceToView(leftimg, 5).centerYEqualToView(leftimg).widthIs(60).heightIs(30);
            
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showRooll)];
            [leftimg addGestureRecognizer:tap];
            leftimg.userInteractionEnabled = YES;
        }else{
            lab.text = @"打印数量";
           
            UIButton *increase = [[UIButton alloc] init];
            increase.tag = 1;
            [increase setImage:[UIImage imageNamed:@"print_button8_default"] forState:0];
            [cell.contentView addSubview:increase];
            [increase addTarget:self action:@selector(updateStampNumber:) forControlEvents:UIControlEventTouchUpInside];
            increase.sd_layout.rightSpaceToView(cell.contentView, 15).centerYEqualToView(cell.contentView).heightIs(22).widthEqualToHeight();
            _stampNum = [[UILabel alloc] init];
            _stampNum.text = _stampInfo[@"printer_times"]?_stampInfo[@"printer_times"]:@"1";
            
            _stampNum.textAlignment = NSTextAlignmentCenter;
             [cell.contentView addSubview:_stampNum];
             _stampNum.sd_layout.rightSpaceToView(increase, 0).centerYEqualToView(cell.contentView).heightIs(22).widthIs(45);
            UIButton *reduce = [[UIButton alloc] init];
            reduce.tag = 0;
            [reduce setImage:[UIImage imageNamed:@"print_button3_default"] forState:0];
            [reduce addTarget:self action:@selector(updateStampNumber:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:reduce];
             reduce.sd_layout.rightSpaceToView(_stampNum, 0).centerYEqualToView(cell.contentView).heightIs(22).widthEqualToHeight();
            
        }
    }else if (indexPath.section == 1){
        if(indexPath.row == 0){
            SNtextfield = [[UITextField alloc] init];
            
            [cell.contentView addSubview:SNtextfield];
            SNtextfield.sd_layout.leftSpaceToView(lab, 5).centerYEqualToView(cell.contentView).rightSpaceToView(cell.contentView, 15).heightIs(30);

            lab.text = @"SN:";
            if(_isNewStamp){
                SNtextfield.placeholder  = @"请填写设备SN";
            }else{
                SNtextfield.text = _stampInfo[@"printer_sn"];
            }
            SNtextfield.delegate = self;
            
            SNtextfield.returnKeyType = UIReturnKeyDone;
        }else{
            Keytextfield = [[UITextField alloc] init];
            SNtextfield.returnKeyType = UIReturnKeyDone;
            [cell.contentView addSubview:Keytextfield];
            Keytextfield.sd_layout.leftSpaceToView(lab, 5).centerYEqualToView(cell.contentView).rightSpaceToView(cell.contentView, 15).heightIs(30);
            Keytextfield.delegate = self;
            Keytextfield.returnKeyType = UIReturnKeyDone;
            lab.text = @"KEY:";
            if(_isNewStamp){
                Keytextfield.placeholder = @"请填写设备KEY";
            }else{
                Keytextfield.text = _stampInfo[@"printer_key"];
            }
            
            
        }
        
    }else{
        UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [cell.contentView addSubview:selectBtn];
        selectBtn.sd_layout.rightSpaceToView(cell.contentView, 30).centerYEqualToView(cell.contentView).widthIs(30).heightEqualToWidth();
        [selectBtn setImage:[UIImage imageNamed:@"print_icon7_default"] forState:UIControlStateNormal];
        [selectBtn setImage:[UIImage imageNamed:@"print_icon4_default"] forState:UIControlStateSelected];
        if(indexPath.row == 0){
            lab.text = @"58mm";
            if([_stampInfo[@"printer_format"] isEqualToString:@"1"]){
                selectBtn.selected = YES;
            }else{
                selectBtn.selected = NO;
            }
        }else{
            lab.text = @"80mm";
            if([_stampInfo[@"printer_format"] isEqualToString:@"2"]){
                selectBtn.selected = YES;
            }else{
                selectBtn.selected = NO;
            }

        }
        lab.textColor = [UIColor lightGrayColor];
    }
    if(indexPath.section == 2){
        lab.sd_layout.leftSpaceToView(cell.contentView, 25);
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *herderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W,40)];
    herderView.backgroundColor = self.view.backgroundColor;
    UILabel *stampLab = [[UILabel alloc] init];
    [herderView addSubview:stampLab];
    stampLab.font = [UIFont systemFontOfSize:15];
    stampLab.textColor = [UIColor lightGrayColor];
    if(section==0){
        stampLab.text = @"打印属性";
    }else if(section==1){
        stampLab.text = @"设备标识";
    }else{
        stampLab.text = @"纸张尺寸";
    }
    stampLab.sd_layout.leftSpaceToView(herderView, 15).centerYEqualToView(herderView).widthIs(150).autoHeightRatio(0);
    return herderView;

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *herderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W,0.5)];
    herderView.backgroundColor = self.view.backgroundColor;
    if(section == 2){
        herderView.height = 250;
        UIButton *savebtn = [[UIButton alloc] init];
        
        [savebtn setTitle:@"保存" forState:UIControlStateNormal];
        [savebtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [savebtn setBackgroundImage:[UIImage imageNamed:@"print_button7_default"] forState:UIControlStateNormal];
        [savebtn addTarget:self action:@selector(saveStampInfo) forControlEvents:UIControlEventTouchUpInside];
        [herderView addSubview:savebtn];
        savebtn.sd_layout.centerXEqualToView(herderView).topSpaceToView(herderView, GETHEIGHT(100)).widthIs(GETWITH(430)).heightIs(GETHEIGHT(80));
        
        UIButton *stamptest = [[UIButton alloc] init];
         [stamptest setBackgroundImage:[UIImage imageNamed:@"print_button6_default"] forState:UIControlStateNormal];
        [stamptest setTitle:@"打印测试" forState:UIControlStateNormal];
        [stamptest setTitleColor:UIColorFromRGB(0x19fdaf) forState:UIControlStateNormal];
        
        [stamptest addTarget:self action:@selector(stampTest) forControlEvents:UIControlEventTouchUpInside];

        [herderView addSubview:stamptest];
        stamptest.sd_layout.centerXEqualToView(herderView).topSpaceToView(savebtn, GETHEIGHT(80)).widthIs(GETWITH(430)).heightIs(GETHEIGHT(80));
        if(_isNewStamp){
            stamptest.hidden = YES;
        }else{
            stamptest.hidden = NO;
        }
    }
    return herderView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section == 2) return 250;
    return 0.5;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    if(textField != SNtextfield) return;
    if(textField.text.length > 3){
        NSString *str = [textField.text substringWithRange:NSMakeRange(3,1)];
        if([str isEqualToString:@"5"]){
            _stampInfo[@"printer_format"] = @"1";
       
            [self.stampTableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
        }else if([str isEqualToString:@"8"]){
            _stampInfo[@"printer_format"] = @"2";
             [self.stampTableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
@end
